<!DOCTYPE html>
<html>

<head>
    <title>line test</title>
    <script type="text/javascript" src="https://unpkg.com/dat.gui@0.7.6/build/dat.gui.min.js"></script>
    <link type="text/css" rel="stylesheet" href="https://unpkg.com/maptalks/dist/maptalks.css">
    <script type="text/javascript" src="https://unpkg.com/maptalks/dist/maptalks.js"></script>
    <script type="text/javascript" src="https://unpkg.com/@maptalks/gl/dist/maptalksgl.js"></script>
    <script type="text/javascript" src="https://unpkg.com/three@0.138.0/build/three.min.js"></script>
    <script type="text/javascript" src="https://unpkg.com/lz-string@1.4.4/libs/lz-string.min.js"></script>
    <script type="text/javascript" src="https://unpkg.com/maptalks.three@latest/dist/maptalks.three.js"></script>
    <script type="text/javascript" src="buildings.js"></script>
    <style>
        html,
        body {
            margin: 0px;
            height: 100%;
            width: 100%;
        }

        #map {
            width: 100%;
            height: 100%;
            background-color: #000;
        }
    </style>
</head>

<body>
    <div id="map"></div>
    <script>

        var map = new maptalks.Map("map", {
            center: [13.416935229170008, 52.529564137540376],
            zoom: 15,
            pitch: 70,
            bearing: 180,

            centerCross: true,
            doubleClickZoom: false,
            baseLayer: new maptalks.TileLayer('tile', {
                urlTemplate: 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
                subdomains: ['a', 'b', 'c', 'd'],
                attribution: '&copy; <a href="http://osm.org">OpenStreetMap</a> contributors, &copy; <a href="https://carto.com/">CARTO</a>'
            })
        });


        // features to draw
        var features = [];

        buildings.forEach(function (b) {
            features = features.concat(b.features);
        });

        // the ThreeLayer to draw buildings
        var threeLayer = new maptalks.ThreeLayer('t', {
            forceRenderOnMoving: true,
            forceRenderOnRotating: true
            // animation: true
        });


        threeLayer.prepareToDraw = function (gl, scene, camera) {
            var light = new THREE.DirectionalLight(0xffffff);
            light.position.set(0, -10, 10).normalize();
            scene.add(light);

            var material = new THREE.MeshBasicMaterial({ color: '#3e35cf' });
            var highlightmaterial = new THREE.MeshBasicMaterial({ color: 'yellow', transparent: true });
            // material.vertexColors = THREE.VertexColors;

            var meshs = [];
            features.forEach(function (g) {
                var heightPerLevel = 10;
                var levels = g.properties.levels || 1;
                var mesh = threeLayer.toExtrudePolygon(maptalks.GeoJSON.toGeometry(g), {
                    height: heightPerLevel * levels,
                    topColor: '#fff'
                }, material);
                //event test
                ['mouseover', 'mouseout'].forEach(function (eventType) {
                    mesh.on(eventType, function (e) {
                        // console.log(e.type, e);
                        // console.log(this);
                        if (e.type === 'mouseout') {
                            this.setSymbol(material);
                        }
                        if (e.type === 'mouseover') {
                            this.setSymbol(highlightmaterial);
                        }
                    });
                });
                // initVertexColors(mesh.geometry, '#2d2f61', '#fff');
                meshs.push(mesh);
                // if (Array.isArray(mesh)) {
                //     scene.add.apply(scene, mesh);
                // } else {
                //     scene.add(mesh);
                // }
            });
            threeLayer.addMesh(meshs);
            addLines();
        };
        const sceneConfig = {
            postProcess: {
                enable: true,
                antialias: { enable: true }
            }
        };
        const groupLayer = new maptalks.GroupGLLayer('group', [threeLayer], { sceneConfig });
        groupLayer.addTo(map);


        var lines;
        var material = new THREE.LineBasicMaterial({
            linewidth: 1,
            color: 0x00ffff,
            // opacity: 0.8,
            transparent: true
        });
        var highlightmaterial = new THREE.LineDashedMaterial({
            linewidth: 1,
            color: 'yellow',
            // opacity: 0.8,
            transparent: true,
            dashSize: 0.05,
            gapSize: 0.05
        });
        function addLines() {
            fetch('./data/berlin-roads.txt').then(function (res) {
                return res.text();
            }).then(function (geojson) {
                geojson = LZString.decompressFromBase64(geojson);
                geojson = JSON.parse(geojson);
                // var material = new THREE.LineDashedMaterial({
                //     linewidth: 1,
                //     color: 0x00ffff,
                //     // opacity: 0.8,
                //     transparent: true,
                //     dashSize: 0.1,
                //     gapSize: 0.1
                // });

                var lineStrings = maptalks.GeoJSON.toGeometry(geojson);
                var timer = 'generate line time';
                console.time(timer);
                lines = lineStrings.slice(0, Infinity).map(function (lineString) {
                    // var colors = [];

                    // var coordinates = lineString.getCoordinates();
                    // for (var i = 0, len = coordinates.length; i < len; i++) {
                    //     var color = new THREE.Color('red');
                    //     color.setHSL(i / len, 1.0, 0.5);
                    //     colors.push(color);
                    // }
                    var line = threeLayer.toLine(lineString, { altitude: 0 }, material);

                    //tooltip test
                    line.setToolTip(line.getId(), {
                        showTimeout: 0,
                        eventsPropagation: true,
                        dx: 10
                    });


                    //infowindow test
                    line.setInfoWindow({
                        content: 'hello world,id:' + line.getId(),
                        title: 'message',
                        animationDuration: 0,
                        autoOpenOn: false
                    });


                    //event test
                    ['click', 'mouseout', 'mouseover', 'mousedown', 'mouseup', 'dblclick', 'contextmenu'].forEach(function (eventType) {
                        line.on(eventType, function (e) {
                            console.log(e.type, e);
                            // console.log(this);
                            if (e.type === 'mouseout') {
                                this.setSymbol(material);
                            }
                            if (e.type === 'mouseover') {
                                this.setSymbol(highlightmaterial);
                            }
                        });
                    });
                    return line;
                });
                console.log('lines.length:', lines.length);
                console.timeEnd(timer);
                threeLayer.addMesh(lines);
                initGui();
                threeLayer.config('animation', true);
            })
        }

        function initGui() {
            var params = {
                add: true,
                color: 0x00ffff,
                show: true,
                opacity: 1,
                altitude: 0
            };
            var gui = new dat.GUI();
            gui.add(params, 'add').onChange(function () {
                if (params.add) {
                    threeLayer.addMesh(lines);
                } else {
                    threeLayer.removeMesh(lines);
                }
            });
            gui.addColor(params, 'color').name('line color').onChange(function () {
                material.color.set(params.color);
                lines.forEach(function (mesh) {
                    mesh.setSymbol(material);
                });
            });
            gui.add(params, 'opacity', 0, 1).onChange(function () {
                material.opacity = params.opacity;
                lines.forEach(function (mesh) {
                    mesh.setSymbol(material);
                });
            });
            gui.add(params, 'show').onChange(function () {
                lines.forEach(function (mesh) {
                    if (params.show) {
                        mesh.show();
                    } else {
                        mesh.hide();
                    }
                });
            });
            gui.add(params, 'altitude', 0, 300).onChange(function () {
                lines.forEach(function (mesh) {
                    mesh.setAltitude(params.altitude);
                });
            });
        }


    </script>
</body>

</html>